package org.example.socket;

import org.example.xuleihuaiol.Student;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 */
public class MyServer {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 创建 ServerSocket
        ServerSocket serverSocket = new ServerSocket(9090);
        Socket client = serverSocket.accept();// 等待客户端连接。。。
        System.out.println("客户端"+client.getInetAddress()+"连接成功！");
        //服务端：先创建输入流对象，在创建输出流
        ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
        ObjectOutputStream oos1 = new ObjectOutputStream(client.getOutputStream());

        while (true){
            // 判断读取的数据中是哪个分支 1查询或2添加。。。
            Data d = (Data)ois.readObject(); //读取客户端写入的数据
            Integer code = d.getCode();
            switch (code){
                case 1:{
                    System.out.println(d.getMsg());
                    ObjectInputStream ois1 = new ObjectInputStream(new FileInputStream("E:/IDEA-file/Java-b.txt"));
                    Data data =(Data) ois1.readObject();
                    Data da = new Data();
                    da.setObj(data.getObj());
                    da.setMsg("返回查询的学生信息");
                    da.setCode(10001);
                    oos1.writeObject(da);
                    oos1.flush();
                    break;
                }
                case 2:{
                    System.out.println(d.getMsg());
                    System.out.println("获取客户端发送的数据："+d);
                    // 将获取到的学生数据，写出到硬盘
                    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:/IDEA-file/Java-b.txt"));
                    oos.writeObject(d);
                    oos.flush();
                    oos.close();// 关闭资源：先开后关
                    System.out.println("成功写入数据！");

                    oos1.writeObject("成功写入数据！");
                    oos1.flush();
                }
            }
        }
    }
}